import {
  createStore
} from 'vuex'

import cart from './modules/cart'
import address from './modules/address'
import order from './modules/order'
import shop from './modules/shop'
import user from './modules/user'

//获取搜索历史
const getHistoryList = () => {
  try {
    if (localStorage.historyList == undefined) {
      localStorage.historyList = []
    }
    return JSON.parse(localStorage.historyList) || []
  } catch (e) {
    return [];
  }
}
const setHistoryList = (state) => {

  const historyListString = JSON.stringify(state.historyList)
  localStorage.historyList = historyListString
}
export default createStore({
  state: {

    historyList: getHistoryList(),

  },
  mutations: {

    //记录搜索历史
    SetHistoryList(state, payload) {

      if (payload.content == '')
        return;
      //先判断元素是否存在
      var index = state.historyList.findIndex((item) => {
        return item == payload.content
      })
      console.log(index);
      if (index > -1) {
        state.historyList.splice(index, 1);

      }
      //表示元素不存在
      if (state.historyList.length > 10) {
        //只保留10个
        state.historyList.splice(0, 1);

      }
      state.historyList.push(payload.content)
      state.historyList = state.historyList.reverse();
      setHistoryList(state);

    },
    //清除搜索记录
    DelteHistoryList(state, payload) {
      state.historyList = [];
      setHistoryList(state);
    },

  },
  actions: {},
  modules: {
    cart,
    address,
    order,
    shop,
    user,
  }
})
